import { defineComponent, ref, watchEffect } from "vue";
import { Button } from "ant-design-vue";
import { useFileService } from "~utils/hooks/upload";



const DocPreview = defineComponent({
  props: ["cache", "url", "fileName", "options", "ext", "visibility"],
  emits: ["complete"],
  setup(props, ctx) {
    const fileUploader = useFileService();
    const iframeRef = ref<HTMLIFrameElement>(null);
    const showiframe = ref(true);

    const listenOfLoad = () => {
      console.log("结束");
      ctx.emit("complete");
    };

    watchEffect(() => {
      try {
        if (props.options.size > 20 * 1024 * 1024) {
          showiframe.value = false;
          ctx.emit("complete");
        }
      } catch (exx) {
        showiframe.value = false;
      } finally {
        setTimeout(() => {
          ctx.emit("complete");
        }, 700);
      }
    });

    const listenOfDownload = () => {
      fileUploader.download.fromUrl(props.url, props.options.name);
    };


    return () => {
      return (
        <>
          {
            showiframe.value
              ? <iframe height={"800px"} width="100%" onLoadeddata={listenOfLoad} ref={iframeRef} onLoad={listenOfLoad} src={"https://view.officeapps.live.com/op/view.aspx?src=" + props.url} frameborder="0"></iframe>
              : <div class="text-center-x" style={{ marginTop: "80px" }}
              >
                <h1 class="mb:14">该文件由于文件太大不支持预览, 请下载到本地进行查看</h1>
                <Button type="primary" onClick={listenOfDownload}>下载文件</Button>
              </div>
          }
        </>
      );
    };
  },
});


export default DocPreview;